package com.myblog.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.myblog.constant.CodeType;
import com.myblog.mapper.UserMapper;
import com.myblog.model.User;
import com.myblog.service.UserService;
import com.myblog.utils.DataMap;
import com.myblog.utils.FileUtilToLocal;
import com.myblog.utils.MD5Util;
import com.myblog.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Random;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisServiceImpl redisService;

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    @Transactional
    public DataMap register(User user) {
        //判断用户名是否已注册
        if(userNameIsExist(user.getUsername())){
            return DataMap.fail(CodeType.USERNAME_EXIST);
        }
        //判断用户名是否规范
        if(user.getUsername().trim().length()>35){
            return DataMap.fail(CodeType.USERNAME_FORMAT_ERROR);
        }
        //判断电话是否存在
        if(userMapper.selectUserByPhone(user.getPhone()) !=null){
            return DataMap.fail(CodeType.PHONE_EXIST);
        }
        user.setUsername(user.getUsername().trim());
        //对传递过来的密码加密
        MD5Util md = new MD5Util();
        user.setPassword(md.encode(user.getPassword()));

        //设置默认头像
        if("male".equals(user.getGender())){
            user.setAvatarImgUrl("www.jd.com");
        }
        else {
            user.setAvatarImgUrl("www.baidu.com");
        }
        //设置登陆时间
        user.setRecentlyLanded("未登录");
        userMapper.addUser(user);
        //注册成功后，配置用户的角色权限信息,默认普通用户
        User userByPhone = userMapper.selectUserByPhone(user.getPhone());
        userMapper.updateRolesByUserId(userByPhone.getId(),1);

        redisService.updateNumOfAllUserNum(userMapper.selectNumOfUser()+1);
        return DataMap.success();
    }

    /**
     * 判断用户是否存在
     * @param username
     * @return
     */
    @Override
    public boolean userNameIsExist(String username) {
        User user = userMapper.selectUserByName(username);
        boolean result = false;
        if(user!=null){
            result =true;
        }
        return result;
    }

    /**
     * 通过用户id判断用户是否有权限
     * @param id
     * @return
     */
    @Override
    public DataMap ifHavePermission(Integer id) {
        if(userMapper.selectUserById(id) == null){
            return DataMap.fail(CodeType.USERNAME_NOT_EXIST);
        }
        //获取用户的权限id
        System.out.println(userMapper.searchUserRole(id));
        List<Integer> roleIds = userMapper.searchUserRole(id);
        System.out.println(roleIds);
        //决定能够写博客的权限
        for (Integer roleId : roleIds) {
            if (roleId == 1 || roleId == 2 || roleId == 3){
                return DataMap.success();
            }
        }
        return DataMap.fail();
    }

    /**
     * 通过用户电话获取用户对象
     * @param phone
     * @return
     */
    @Override
    public User searchUserByPhone(String phone) {
        User user = userMapper.selectUserByPhone(phone);

        return user;
    }

    @Override
    public DataMap getUserPersonInfo(String username) {
        User user = userMapper.selectUserByName(username);
        //处理图片路径
        String avatarImgUrl = user.getAvatarImgUrl();
        if(avatarImgUrl.length()>20) {
            int begin = avatarImgUrl.indexOf("images");
            String useAvatarImgUrl = avatarImgUrl.substring(begin - 1);
            user.setAvatarImgUrl(useAvatarImgUrl);
        }

        return DataMap.success(CodeType.SUCCESS_STATUS).setData(user);
    }

    @Override
    public DataMap sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.如果不符合返回
            return DataMap.fail(CodeType.PHONE_ERROR);
        }
        //3.符合，生成验证码
        String code = RandomUtil.randomNumbers(6);
        //4.保存验证码到session
        session.setAttribute("code",code);
        //5.发送验证码
        System.out.println("发送验证码成功，验证码："+code);
        return DataMap.success();
    }

    @Override
    public DataMap changePhoneAndPassword(String phone, String newPassword, Integer userId, String code, HttpSession session){
        //校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            return DataMap.fail(CodeType.PHONE_ERROR);
        }
        //查询手机是否已存在
        if(userMapper.selectUserByPhone(phone)==null){
            return DataMap.fail(CodeType.PHONE_NOT_EXIST);
        }
        //校验验证码
        Object cacheCode = session.getAttribute("code");
        if (cacheCode == null || !cacheCode.toString().equals(code)){
            //不一致，或者验证码过期不存在
            return DataMap.fail(CodeType.AUTH_CODE_ERROR);
        }
        //对传过来的密码进行处理
        MD5Util md = new MD5Util();
        String MdPassword = md.encode(newPassword);
        //手机号是否改变
        if (userMapper.selectUserPhoneById(userId).equals(phone)) {
            //手机号码一致
            //根据用户id修改密码
            userMapper.updatePassword(userId,MdPassword);
        }
        else {
            //手机号不一致
            //根据用户id修改密码和手机号
            userMapper.updatePhoneAndPassword(userId,phone,MdPassword);
        }

        return DataMap.success();
    }

    @Override
    public DataMap saveUserByUserPhone(String phone, User user) {
        if(userMapper.selectUserByName(user.getUsername())!=null){
            return DataMap.fail(CodeType.USERNAME_EXIST);
        }
        User newUser = userMapper.selectUserByPhone(phone);
        if(user.getUsername().equals(newUser.getUsername())){
            newUser.setTrueName(user.getTrueName());
            newUser.setBirthday(user.getBirthday());
            newUser.setGender(user.getGender());
            newUser.setEmail(user.getEmail());
            newUser.setPersonalBrief(user.getPersonalBrief());
            userMapper.updateUserByPhoneNoUserName(newUser);
            return DataMap.success(CodeType.NOT_MODIFY_USERNAME);
        }
        else {
            newUser.setUsername(user.getUsername());
            newUser.setTrueName(user.getTrueName());
            newUser.setBirthday(user.getBirthday());
            newUser.setGender(user.getGender());
            newUser.setEmail(user.getEmail());
            newUser.setPersonalBrief(user.getPersonalBrief());

            userMapper.updateUserByPhone(newUser);
            return DataMap.success(CodeType.HAS_MODIFY_USERNAME);
        }
    }

    @Override
    public DataMap changeUserImgByUsername(User user, MultipartFile img) {
        //上传本地
        String imgUrl = null;
        try {
            imgUrl = FileUtilToLocal.uploadToLocal(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //文件中删除掉之前的头像
        String oldAva = userMapper.selectAvatarImgUrlById(user.getId());
        FileUtilToLocal fileUtil = new FileUtilToLocal();
        fileUtil.deleteFiles(oldAva);
        //更新新头像的路径到数据库
        userMapper.updateAvatarImgByPhone(user.getPhone(),imgUrl);
        return DataMap.success();
    }

    @Override
    public DataMap forgetChangePhoneAndPassword(String phone, String newPassword, HttpSession session) {
        //校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            return DataMap.fail(CodeType.PHONE_ERROR);
        }
        //查询手机是否注册
        if(userMapper.selectUserByPhone(phone)==null){
            return DataMap.fail(CodeType.PHONE_NOT_EXIST);
        }
//        //校验验证码
//        Object cacheCode = session.getAttribute("code");
//        if (cacheCode == null || !cacheCode.toString().equals(code)){
//            //不一致，或者验证码过期不存在
//            return DataMap.fail(CodeType.AUTH_CODE_ERROR);
//        }
        //对传过来的密码进行处理
        MD5Util md = new MD5Util();
        String MdPassword = md.encode(newPassword);
        //获取将要修改的用户id
        Integer userId = userMapper.selectUserIdByPhone(phone);
        //修改密码
        userMapper.updatePhoneAndPassword(userId,phone,MdPassword);
        //修改成功后重新登陆
        return DataMap.success();
    }

    @Override
    public User searchUserByName(String name) {
        User user = userMapper.selectUserByName(name);

        return user;
    }

    @Override
    public DataMap saveUserByUserName(String name, User user) {
        if(userMapper.selectUserByName(user.getUsername())!=null){
            return DataMap.fail(CodeType.USERNAME_EXIST);
        }
        User newUser = userMapper.selectUserByName(name);
        if(user.getUsername().equals(newUser.getUsername())){
            newUser.setTrueName(user.getTrueName());
            newUser.setBirthday(user.getBirthday());
            newUser.setGender(user.getGender());
            newUser.setEmail(user.getEmail());
            newUser.setPersonalBrief(user.getPersonalBrief());
            userMapper.updateUserByPhoneNoUserName(newUser);
            return DataMap.success(CodeType.NOT_MODIFY_USERNAME);
        }
        else {
            newUser.setUsername(user.getUsername());
            newUser.setTrueName(user.getTrueName());
            newUser.setBirthday(user.getBirthday());
            newUser.setGender(user.getGender());
            newUser.setEmail(user.getEmail());
            newUser.setPersonalBrief(user.getPersonalBrief());

            userMapper.updateUserByPhone(newUser);
            return DataMap.success(CodeType.HAS_MODIFY_USERNAME);
        }
    }

    @Override
    public DataMap changePhoneByOldPhone(String phone, String newPhone, Integer id, String authCode, HttpSession session) {
        //校验手机号
        if(RegexUtils.isPhoneInvalid(newPhone)){
            return DataMap.fail(CodeType.PHONE_ERROR);
        }
        //查询手机是否已存在
        if(userMapper.selectUserByPhone(newPhone)!=null){
            return DataMap.fail(CodeType.PHONE_EXIST);
        }
        //校验验证码
        Object cacheCode = session.getAttribute("code");
        if (cacheCode == null || !cacheCode.toString().equals(authCode)){
            //不一致，或者验证码过期不存在
            return DataMap.fail(CodeType.AUTH_CODE_ERROR);
        }
        //手机号不一致
        //根据用户id手机号
        userMapper.updatePhoneById(id,newPhone);
        return DataMap.success();
    }


}
